<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;

class User extends Model
{
    // 获取所有用户
    public function allUser($map, $offset, $limit)
    {
        return $this->where($map)->limit($offset,$limit)->select();
    }

    // 获取账户信息
    public static function getByOpenid($openid)
    {
        return self::get(['openid' => $openid]);
    }

    // 添加 微信账号
    public static function addWechatUser($data)
    {
        // 注册微信 用户
        $userData = [
            'nickname'      => $data['nickname'],
            'avatar'        => $data['headimgurl'],
            'openid'        => $data['openid'],
            'sex'           => $data['sex'],
            'create_time'   => time(),
        ];

        $user = self::create($userData);

        // 添加账户
        UserAccount::add($user->id);
        return $user;
    }

    public function changeBalance($openId, $amount, $orderNo = '', $type)
    {
        if($orderNo && UserAccountRecord::get(['order_no' => $orderNo])) return true;
        $user = self::get(['openid' => $openId]);
        $account = UserAccount::get(['user_id' => $user['id']]);
        if(in_array($type, UserAccountRecord::$addAmount)) {
            UserAccountRecord::create([
                'user_id' => $user['id'],
                'change' => $amount,
                'balance' => $account->balance + $amount,
                'order_no' => $orderNo,
                'type' => $type,
                'create_time' => time(),
            ]);
            $account->add_amount += $amount;
            $account->balance += $amount;
            $account->save();
        } else {
            UserAccountRecord::create([
                'user_id' => $user['id'],
                'change' => - $amount,
                'balance' => $account->balance - $amount,
                'order_no' => $orderNo,
                'type' => $type,
                'create_time' => time(),
            ]);
            $account->del_amount += $amount;
            $account->balance -= $amount;
            $account->save();
        }
        return true;
    }

    // 关联 账户
    public function account()
    {
        return $this->hasOne('UserAccount');
    }
}
